<?php

define('ROOT_PATH', __DIR__);
define('CACHE_PATH', ROOT_PATH.DIRECTORY_SEPARATOR.'cache');

try {

    $configFile = ROOT_PATH.DIRECTORY_SEPARATOR.'/config.php';

    if(is_file($configFile)){
        require_once $configFile;
    }

    if(!defined('SITE_LOG_PATH')){
        throw new Exception('未配置日志目录.');
    }

    $ipArr = [];

    foreach (getLogFiles(SITE_LOG_PATH) as $logFile) {
        getIpsByLogFile($logFile, $ipArr);
    }
    // ip去重
    $ipArr = array_unique($ipArr);

    $whiteIPFile = CACHE_PATH . DIRECTORY_SEPARATOR . 'whiteIPList.log';
    $whiteIPList = getIPByCache($whiteIPFile);

    $blackIPFile = CACHE_PATH . DIRECTORY_SEPARATOR . 'blackIPList.log';
    $blackIPList = getIPByCache($blackIPFile);


    require_once ROOT_PATH.'/filter/FileFilter.php';
    $filter = new FileFilter();

    //循环ip
    foreach ($ipArr as $ip) {
        if (in_array($ip, $whiteIPList) || in_array($ip, $blackIPList)) {
            continue;
        }

        if (!$filter->isChinaIP($ip)) {
            $blackList[] = $ip;
            $blackIPList[] = $ip;
        } else {
            $whiteIPList[] = $ip;
        }
    }

    file_put_contents($whiteIPFile, implode(',', $whiteIPList));
    file_put_contents($blackIPFile, implode(',', $blackIPList));
    echo !empty($blackList) ? implode(PHP_EOL, $blackList) : null;

} catch (\Throwable $e) {
    $content = [
        'code'    => $e->getCode(),
        'message' => $e->getMessage(),
        'line'    => $e->getLine(),
        'trace'   => $e->getTraceAsString(),
    ];
    file_put_contents(CACHE_PATH . DIRECTORY_SEPARATOR . 'error.log', print_r($content, 1), FILE_APPEND);
    exit();
}

/**
 * 获取日志文件地址
 * getLogFiles
 * @param $path
 * @return array
 */
function getLogFiles($path)
{
    if (!is_dir($path)) {
        return [];
    }
    $data = scandir($path);
    foreach ($data as $value) {
        $file = $path . DIRECTORY_SEPARATOR . $value;
        $fileInfo = pathinfo($file);
        if (is_file($file) && !empty($fileInfo['extension']) && $fileInfo['extension'] == 'log') {
            $logFiles[] = $file;
        }
    }
    return !empty($logFiles)?$logFiles:[];
}

/**
 * 获取ip
 * getIpsByLogFile
 * @param $logFile
 * @param $ipArr
 * @return array
 */
function getIpsByLogFile($logFile, &$ipArr)
{
    $f = fopen($logFile, 'r');
    while (!feof($f)) {
        $str = fread($f, 1024 * 1024 * 2);
        $lines = explode("\n", $str);
        foreach ($lines as $line) {
            if (!$line) {
                continue;
            }
            $ip = substr($line, 0, strpos($line, '- -') - 1);
            if (ip2long($ip) === false) {
                continue;
            }
            $ipArr[] = $ip;
        }
    }
    fclose($f);
    return $ipArr;
}

/**
 * getIPByCache
 * @param $file
 * @return array
 */
function getIPByCache($file)
{
    $res = @file_get_contents($file) ?: null;
    return $res ? explode(',', $res) : [];
}